<template>
  <div class="post-review-container">
    <a-spin :spinning="loading">
      <!-- 空状态 -->
      <a-empty
        v-if="!loading && filteredTeams.length === 0"
        :description="noTeamText"
        class="empty-tip"
      />

      <!-- 战队标签页 -->
      <a-tabs v-model:activeKey="activeTeamId" @change="handleTeamChange" v-else>
        <a-tab-pane 
          v-for="team in filteredTeams" 
          :key="team.id"
        >
          <!-- 自定义标签内容 -->
          <template #tab>
            <span class="custom-tab">
              <span class="team-name">{{ team.teamName }}</span>
              <a-badge 
                v-if="activeTeamId === team.id && pendingPosts.length > 0"
                :count="pendingPosts.length" 
                :number-style="{ backgroundColor: '#52c41a' }"
              />
            </span>
          </template>

          <!-- 帖子审核区域 -->
          <div class="post-review-section">
            <div class="section-header">
              <h3>待审核帖子 ({{ pendingPosts.length }})</h3>
              <div class="search-bar">
                <a-input-search
                  v-model:value="searchParams.title"
                  placeholder="搜索帖子标题"
                  style="width: 300px"
                  @search="fetchPendingPosts"
                  allow-clear
                />
                <a-button 
                  type="primary" 
                  @click="handleRefresh"
                  :loading="postLoading"
                >
                  <template #icon><reload-outlined /></template>
                  刷新
                </a-button>
              </div>
            </div>

            <a-spin :spinning="postLoading">
              <a-empty
                v-if="pendingPosts.length === 0"
                description="暂无待审核帖子"
                class="empty-tip"
              />

              <a-list
                v-else
                :data-source="pendingPosts"
                bordered
                item-layout="vertical"
              >
                <template #renderItem="{ item }">
                  <a-list-item class="post-item">
                    <template #actions>
                      <a-space>
                        <a-tooltip title="通过后将变为已发布状态">
                          <a-button 
                            type="primary" 
                            @click="handleReview(item, 1)"
                            :loading="reviewLoading[item.id]?.approve"
                          >
                            通过
                          </a-button>
                        </a-tooltip>
                        <a-tooltip title="拒绝后将变为已下架状态">
                          <a-button 
                            danger 
                            @click="handleReview(item, 3)"
                            :loading="reviewLoading[item.id]?.reject"
                          >
                            拒绝
                          </a-button>
                        </a-tooltip>
                        <a-tooltip title="彻底删除该帖子">
                          <a-button 
                            type="dashed" 
                            @click="handleReview(item, 4)"
                            :loading="reviewLoading[item.id]?.delete"
                          >
                            删除
                          </a-button>
                        </a-tooltip>
                      </a-space>
                    </template>
                    <a-list-item-meta>
                      <template #title>
                        <div class="post-title">
                          <span>{{ item.title }}</span>
                          <a-tag :color="getStatusColor(item.status)">
                            {{ getStatusText(item.status) }}
                            <a-tooltip v-if="item.status === 2" title="待审核状态">
                              <question-circle-outlined style="margin-left: 4px"/>
                            </a-tooltip>
                          </a-tag>
                        </div>
                      </template>
                      <template #description>
                        <div class="post-info">
                          <div><span class="label">帖子ID:</span> {{ item.id }}</div>
                          <div><span class="label">发布时间:</span> {{ formatDate(item.publishTime) }}</div>
                          <div><span class="label">最后更新:</span> {{ formatDate(item.updateTime) }}</div>
                          <div><span class="label">标签:</span> 
                            <a-tag v-for="tag in parseTagIds(item.tagIds)" :key="tag" color="blue">
                              {{ tag }}
                            </a-tag>
                          </div>
                        </div>
                      </template>
                    </a-list-item-meta>
                    <div class="post-content">
                      <div class="content-preview" v-html="item.content"></div>
                      <a-button type="link" @click="viewFullContent(item)" size="small">查看全文</a-button>
                    </div>
                  </a-list-item>
                </template>
              </a-list>
              <div class="pagination">
                <a-pagination
                  v-model:current="searchParams.current"
                  v-model:pageSize="searchParams.pageSize"
                  :total="total"
                  :show-total="total => `共 ${total} 条`"
                  show-size-changer
                  @change="fetchPendingPosts"
                />
              </div>
            </a-spin>
          </div>
        </a-tab-pane>
      </a-tabs>
    </a-spin>

    <!-- 帖子内容详情模态框 -->
    <a-modal 
      v-model:visible="contentModal.visible" 
      :title="contentModal.title" 
      width="70%"
      :footer="null"
    >
      <div class="full-content" v-html="contentModal.content"></div>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { message, Modal } from 'ant-design-vue';
import { ReloadOutlined, QuestionCircleOutlined } from '@ant-design/icons-vue';
import dayjs from 'dayjs';
import { getUnauditedPostPageList, reviewPost } from '@/api/bizPostController';
import { findMyTeams } from '@/api/sysTeamController';

// 数据状态
const myTeams = ref([]);
const activeTeamId = ref(null);
const pendingPosts = ref([]);
const loading = ref(false);
const postLoading = ref(false);
const reviewLoading = ref({});
const total = ref(0);
const contentModal = ref({
  visible: false,
  title: '',
  content: ''
});

// 搜索参数
const searchParams = ref({
  current: 1,
  pageSize: 10,
  title: ''
});

// 状态颜色映射
const getStatusColor = (status) => {
  const statusMap = {
    0: 'default',  // 草稿 - 灰色
    1: 'green',    // 已发布 - 绿色
    2: 'orange',   // 审核中 - 橙色
    3: 'red',      // 已下架 - 红色
    4: 'gray'      // 已删除 - 深灰
  };
  return statusMap[status] || 'default';
};

// 状态文本映射
const getStatusText = (status) => {
  const statusMap = {
    0: '草稿',
    1: '已发布',
    2: '审核中',
    3: '已下架',
    4: '已删除'
  };
  return statusMap[status] || '未知';
};

// 计算属性
const filteredTeams = computed(() => {
  return myTeams.value;
});

const noTeamText = computed(() => {
  return myTeams.value.length === 0 
    ? '您还没有创建任何战队' 
    : '没有需要审核帖子的战队';
});

// 查看完整内容
const viewFullContent = (post) => {
  contentModal.value = {
    visible: true,
    title: `帖子详情 - ${post.title}`,
    content: post.content
  };
};

// 格式化日期
const formatDate = (date) => {
  return date ? dayjs(date).format('YYYY-MM-DD HH:mm') : '未知时间';
};

// 解析标签ID
const parseTagIds = (tagIds) => {
  if (!tagIds) return [];
  try {
    return tagIds.split(',').filter(Boolean);
  } catch {
    return [];
  }
};

// 刷新功能
const handleRefresh = () => {
  searchParams.value = {
    current: 1,
    pageSize: 10,
    title: ''
  };
  fetchPendingPosts();
};

// 获取我创建的战队列表
const fetchMyTeams = async () => {
  try {
    loading.value = true;
    const { data } = await findMyTeams();
    myTeams.value = data.data || [];
    
    if (myTeams.value.length > 0) {
      activeTeamId.value = myTeams.value[0].id;
      await fetchPendingPosts();
    }
  } catch (error) {
    console.error('获取战队列表失败:', error);
    message.error('获取战队列表失败，请检查网络');
  } finally {
    loading.value = false;
  }
};

// 获取待审核帖子
const fetchPendingPosts = async () => {
  try {
    postLoading.value = true;
    const user = JSON.parse(localStorage.getItem('userInfo'));
    const params = {
      current: searchParams.value.current,
      pageSize: searchParams.value.pageSize,
      userId: user.userId,
      title: searchParams.value.title
    };
    
    const { data } = await getUnauditedPostPageList(params);
    if (data?.code === 0) {
      pendingPosts.value = data.data?.list || [];
      total.value = data.data?.total || 0;
      
      // 前端按战队ID过滤
      if (activeTeamId.value) {
        pendingPosts.value = pendingPosts.value.filter(
          post => post.teamId === activeTeamId.value
        );
      }
    } else {
      message.error(data?.message || '获取帖子列表失败');
    }
  } catch (error) {
    console.error('获取帖子列表失败:', error);
    message.error('获取帖子列表失败，请稍后重试');
  } finally {
    postLoading.value = false;
  }
};

// 切换战队
const handleTeamChange = (teamId) => {
  activeTeamId.value = teamId;
  fetchPendingPosts();
};

// 审核帖子
const handleReview = (post, status) => {
  const actionMap = {
    1: { text: '通过', desc: '通过后帖子将变为已发布状态', statusText: '已发布' },
    3: { text: '拒绝', desc: '拒绝后帖子将变为已下架状态', statusText: '已下架' },
    4: { text: '删除', desc: '帖子将被彻底删除，不可恢复', statusText: '已删除' }
  };
  
  Modal.confirm({
    title: `确认${actionMap[status].text}该帖子?`,
    content: `确定要${actionMap[status].text}帖子【${post.title}】吗？`,
    okText: `确认${actionMap[status].text}`,
    cancelText: '取消',
    onOk: async () => {
      try {
        reviewLoading.value = {
          ...reviewLoading.value,
          [post.id]: { 
            approve: status === 1,
            reject: status === 3,
            delete: status === 4
          }
        };
        
        const { data } = await reviewPost({
          teamId: activeTeamId.value,
          id: post.id,
          status
        });
        
        if (data?.code === 0) {
          message.success(`已${actionMap[status].text}该帖子`);
          await fetchPendingPosts();
        } else {
          message.error(data?.message || '操作失败');
        }
      } catch (error) {
        console.error('审核操作失败:', error);
        message.error('操作失败，请稍后重试');
      } finally {
        reviewLoading.value = {
          ...reviewLoading.value,
          [post.id]: { 
            approve: false,
            reject: false,
            delete: false
          }
        };
      }
    }
  });
};

// 初始化加载
onMounted(() => {
  fetchMyTeams();
});
</script>

<style scoped>
.post-review-container {
  padding: 24px;
  min-height: calc(100vh - 48px);
}

.custom-tab {
  display: inline-flex;
  align-items: center;
  gap: 8px;
}

.team-name {
  margin-right: 4px;
}

.post-review-section {
  background: #fff;
  padding: 24px;
  border-radius: 8px;
  margin-top: 16px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.search-bar {
  display: flex;
  gap: 16px;
  align-items: center;
}

.post-item {
  padding: 16px;
  transition: all 0.2s;
}

.post-item:hover {
  background: #fafafa;
}

.post-title {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 16px;
  font-weight: 500;
}

.post-info {
  display: flex;
  flex-direction: column;
  gap: 6px;
  font-size: 13px;
}

.post-content {
  margin-top: 12px;
  color: rgba(0, 0, 0, 0.85);
  line-height: 1.6;
}

.content-preview {
  max-height: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 6;
  -webkit-box-orient: vertical;
}

.label {
  color: rgba(0, 0, 0, 0.45);
  margin-right: 8px;
  display: inline-block;
  min-width: 60px;
}

.pagination {
  margin-top: 16px;
  text-align: right;
}

.empty-tip {
  margin: 40px 0;
  padding: 40px 0;
  background: #fff;
  border-radius: 8px;
}

.full-content {
  max-height: 60vh;
  overflow-y: auto;
  padding: 12px;
}
</style>